package com.ruoyi.web.controller.monitor;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.session.TokenSign;
import cn.dev33.satoken.stp.StpUtil;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.websocket.WebSocketUsers;
import com.ruoyi.system.domain.SysUserOnline;
import com.ruoyi.system.service.ISysUserOnlineService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 在线用户监控
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/monitor/online")
public class SysUserOnlineController extends BaseController {
    @Autowired
    private ISysUserOnlineService userOnlineService;

    @Autowired
    private RedisCache redisCache;

    @SaCheckPermission("monitor:online:list")
    @GetMapping("/list")
    public TableDataInfo list(String ipaddr, String userName) {
        // 获取所有已登录的会话id
        List<String> sessionIdList = StpUtil.searchSessionId("", 0, -1, false);

        List<SysUserOnline> userOnlineList = new ArrayList<>();
        for (String sessionId : sessionIdList) {
            // 根据会话id，查询对应的 SaSession 对象，此处一个 SaSession 对象即代表一个登录的账号
            SaSession session = StpUtil.getSessionBySessionId(sessionId);
            LoginUser loginUser = (LoginUser) session.get("loginUser");
            loginUser.setToken(sessionId);

            SysUserOnline sysUserOnline = null;
            if (StringUtils.isNotEmpty(ipaddr) && StringUtils.isNotEmpty(userName)) {
                sysUserOnline = userOnlineService.selectOnlineByInfo(ipaddr, userName, loginUser);
            } else if (StringUtils.isNotEmpty(ipaddr)) {
                sysUserOnline = userOnlineService.selectOnlineByIpaddr(ipaddr, loginUser);
            } else if (StringUtils.isNotEmpty(userName) && StringUtils.isNotNull(loginUser.getUser())) {
                sysUserOnline = userOnlineService.selectOnlineByUserName(userName, loginUser);
            } else {
                sysUserOnline = userOnlineService.loginUserToUserOnline(loginUser);
            }

            // 查询这个账号都在哪些设备登录了
            List<TokenSign> tokenSignList = session.getTokenSignList();
            for (TokenSign tokenSign : tokenSignList) {
                tokenSign.setTag(2342342);
            }
            if (sysUserOnline != null) {
                sysUserOnline.setCount(tokenSignList.size());
                userOnlineList.add(sysUserOnline);
            }
        }
        return getDataTable(userOnlineList);
    }

    /**
     * 强退用户
     */
    @SaCheckPermission("monitor:online:forceLogout")
    @Log(title = "在线用户", businessType = BusinessType.FORCE)
    @DeleteMapping("/{tokenId}")
    public AjaxResult forceLogout(@PathVariable String tokenId) throws IOException {
        SaSession session = StpUtil.getSessionBySessionId(tokenId);
        List<TokenSign> tokenSignList = session.getTokenSignList();
        for (TokenSign tokenSign : tokenSignList) {
            StpUtil.logoutByTokenValue(tokenSign.getValue());
            WebSocketUsers.close(tokenSign.getValue());
        }
        return success();
    }
}
